// pages/login/login.js
const app = getApp()
import { login } from '../../utils/auth.js'

Page({
  data: {
    username: '',
    password: '',
    showPassword: false,
    isLoading: false
  },
  onLoad() {
    // 检查是否已登录
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo) {
      this.redirectToHome(userInfo.type)
    }
  },
  handleUsernameInput(e) {
    this.setData({
      username: e.detail.value
    })
  },
  handlePasswordInput(e) {
    this.setData({
      password: e.detail.value
    })
  },
  togglePassword() {
    this.setData({
      showPassword: !this.data.showPassword
    })
  },
  async handleLogin() {
    const { username, password, isLoading } = this.data
    
    if (isLoading) return
    
    if (!username || !password) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      })
      return
    }
    
    this.setData({ isLoading: true })
    wx.showLoading({ title: '登录中...' })
    
    try {
      // 不传递userType参数，后端会自动根据数据库中的用户类型识别
      const result = await login(username, password)
      wx.hideLoading()
      
      if (result.success) {
        app.globalData.userInfo = result.data.userInfo
        app.globalData.token = result.data.token
        app.globalData.userType = result.data.userInfo.type
        
        wx.showToast({
          title: '登录成功',
          icon: 'success'
        })
        
        setTimeout(() => {
          this.redirectToHome(result.data.userInfo.type)
        }, 500)
      } else {
        throw new Error(result.message || '登录失败')
      }
    } catch (error) {
      this.setData({ isLoading: false })
      wx.hideLoading()
      wx.showToast({
        title: error.message || '登录失败',
        icon: 'none',
        duration: 2000
      })
    }
  },
  redirectToHome(userType) {
    if (userType === 'teacher') {
      wx.reLaunch({ url: '/pages/teacher/home/home' })
    } else {
      wx.reLaunch({ url: '/pages/student/home/home' })
    }
  }
})
